package com.villaday.idf.fragment;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import androidx.annotation.RequiresApi;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.activity.BackHandlerHelper;
import com.villaday.idf.activity.FragmentBackHandler;
import com.villaday.idf.adapter.FodderAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.DividerGridItem;
import com.villaday.idf.custom.ErWeiMaDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.custom.YiJianTuiGuangDialog;
import com.villaday.idf.model.Collect;
import com.villaday.idf.model.Material_postersEntity202;
import com.villaday.idf.model.behaviorsEntity;
import com.villaday.idf.model.house_materialEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import byc.imagewatcher.ImageWatcher;
import byc.imagewatcher.MessagePicturesLayout;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * 素材
 */
public class FodderHouseFragment extends BaseFragment implements View.OnClickListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, OkHttpUtil.OnDataListener, BaseDialog.OnItemClickListener, MessagePicturesLayout.Callback, FragmentBackHandler, ImageWatcher.OnPictureLongPressListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.v_fit)
    View v_fit;
    @BindView(R.id.ll)
    LinearLayout ll;


    private FodderAdapter fodderAdapter;
    private String houseId;

    private Gson gson = new GsonBuilder().create();
    private com.villaday.idf.model.house_materialEntity house_materialEntity;
    private LoadingDialog loadingDialog;
    private ImageWatcher vImageWatcher;
    private String persellId;
    private StatusLayoutManager statusLayoutManager;


    public FodderHouseFragment() {
        // Required empty public constructor
    }

    public static FodderHouseFragment instance(String houseId, String persellId, String brokerAge, boolean presellProduct) {
        FodderHouseFragment homeFragment = new FodderHouseFragment();
        Bundle bundle = new Bundle();
        bundle.putString("houseId", houseId);
        bundle.putString("persellId", persellId);
        bundle.putString("brokerAge", brokerAge);
        bundle.putBoolean("presellProduct", presellProduct);

        homeFragment.setArguments(bundle);
        return homeFragment;
    }

    @Override
    protected int getViewResId() {
        return R.layout.fragment_fodder_house;
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void init(View v) {

        srl.setOnRefreshListener(this);
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        fodderAdapter = new FodderAdapter(getContext(), this, this, getActivity());
        fodderAdapter.setPictureClickCallback(this);
        rv.setAdapter(fodderAdapter);
        rv.addItemDecoration(new DividerGridItem(getContext()));
        // rv.addItemDecoration(new SpaceItemDecoration(getContext()).setSpace(14).setSpaceColor(0xFFECECEC));

        fodderAdapter.setOnItemClickListener(this);
        fodderAdapter.setEmptyView(R.layout.empty_tips);
        fodderAdapter.setEmptyTips(R.id.tv_emptyTips, "暂无数据");
        //设置空白页
        statusLayoutManager = setupDefaultStatusLayoutManager(ll, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadData();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
    }


    @Override
    protected void loadData() {


        persellId = getArguments().getString("persellId");

        houseId = getArguments().getString("houseId");

        if (getArguments().getBoolean("presellProduct")) {
            OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.presell_material, persellId), this);

        } else {
            OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.house_material, houseId), this);


        }


    }

    @Override
    public void onClick(final View view) {


        switch (view.getId()) {
            case R.id.img_collect: {//收藏
                loadingDialog = LoadingDialog.newInstance("操作中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                /*final behaviors behaviors = new behaviors(data.get((Integer) view.getTag()).isFavorite() ? 107 : 106
                        , new behaviors.ContextEntity(104, data.get((Integer) view.getTag()).getId()));
*/
                Collect collect = new Collect(!house_materialEntity.getBody().get((Integer) view.getTag()).isFavorite());
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(getContext(), String.format(Constant.URL.member_collect, "54", house_materialEntity.getBody().get((Integer) view.getTag()).getId()), collect, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        dismissLoading();

                        LogeUtil.e("member_collect", json);
                        behaviorsEntity behaviorsEntity = gson.fromJson(json, behaviorsEntity.class);

                        if (behaviorsEntity.getBody().getStatus() == 1) {
                            house_materialEntity.getBody().get((Integer) view.getTag()).setFavorite(!house_materialEntity.getBody().get((Integer) view.getTag()).isFavorite());

                            //dynamicListAdapter.notifyItemChanged((Integer) view.getTag());
                            fodderAdapter.notifyDataSetChanged();
                            ToastUtil.initToast(getContext(), house_materialEntity.getBody().get((Integer) view.getTag()).isFavorite() ? "收藏成功" : "已取消收藏");

                        } else if (behaviorsEntity.getBody().getStatus() == 0) {

                            ToastUtil.initToast(getContext(), "操作失败");

                        } else {
                            ToastUtil.initToast(getContext(), "操作失败");

                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });
            }
            break;
            case R.id.tv_erweima: {//二维码
                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;

                mClipData = ClipData.newPlainText("test", house_materialEntity.getBody().get((Integer) view.getTag()).getAdWord());
                mClipboardManager.setPrimaryClip(mClipData);


                loadingDialog = LoadingDialog.newInstance("跳转中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                String materialId = house_materialEntity.getBody().get((Integer) view.getTag()).getId();
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("modelType", house_materialEntity.getBody().get((Integer) view.getTag()).getModelType() + "");
                OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.material_posters, materialId), hashMap, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        if (!TextUtils.isEmpty(json)) {
                            dismissLoading();
                            Material_postersEntity202 material_postersEntity = gson.fromJson(json, Material_postersEntity202.class);
                            if ("200".equals(material_postersEntity.getCode())) {
                                LogeUtil.e("material_posters" + json);
                                ErWeiMaDialog erWeiMaDialog = ErWeiMaDialog.newInstance(material_postersEntity.getBody().getPoster());
                                erWeiMaDialog.show(getActivity().getFragmentManager());

                                erWeiMaDialog.setOnItemClickListener(FodderHouseFragment.this);
                            } else {
                                ToastUtil.initToast(getContext(), material_postersEntity.getMsg());
                            }
                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });


            }
            break;


            case R.id.tv_share1: {//一键发圈


                if (house_materialEntity.getBody().get((Integer) view.getTag()).getEnablePoster() == 0) {//enablePoster(1:可以生成 0:无法生成),
                    ToastUtil.initToast(getContext(), "分享文案已复制，去粘贴");

                    YiJianTuiGuangDialog yiJianTuiGuangDialog = YiJianTuiGuangDialog.newInstance(house_materialEntity.getBody().get((Integer) view.getTag()).getHouse().getBrokerAge());
                    yiJianTuiGuangDialog.show(getActivity().getFragmentManager());
                    yiJianTuiGuangDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                        @Override
                        public void onItemClick(View v) {
                            ClipboardManager mClipboardManager = mClipboardManager =
                                    (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                            ClipData mClipData;

                            mClipData = ClipData.newPlainText("test", house_materialEntity.getBody().get((Integer) view.getTag()).getAdWord());
                            mClipboardManager.setPrimaryClip(mClipData);
                            switch (v.getId()) {
                                case R.id.tv_wx: {
                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                    List<String> lists = new ArrayList<String>();
                                    lists.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());
                                    ShareUtilse.shareImage(getContext(),0, lists,lists.get(lists.size()-1),"");

                                }

                                break;
                                case R.id.tv_pyq: {
                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                    List<String> lists = new ArrayList<String>();
                                    lists.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());
                                    ShareUtilse.shareImage(getContext(),1, lists,lists.get(lists.size()-1),"");

                                }
                                break;
                                case R.id.tv_YJTG_save: {
                                    List<String> picList = new ArrayList<>();
                                    picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());
                                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                                    saveImageForRecursive(picList, picList.size(), loadingDialog);
                                }
                            }
                        }
                    });


                } else {
                    loadingDialog = LoadingDialog.newInstance("跳转中");
                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                    String materialId = house_materialEntity.getBody().get((Integer) view.getTag()).getId();
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("modelType", house_materialEntity.getBody().get((Integer) view.getTag()).getModelType() + "");
                    OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.material_posters, materialId), hashMap, new OkHttpUtil.OnDataListener() {
                        @Override
                        public void onResponse(String url, String json) {
                            if (!TextUtils.isEmpty(json)) {
                                dismissLoading();
                                final Material_postersEntity202 material_postersEntity = gson.fromJson(json, Material_postersEntity202.class);
                                if ("200".equals(material_postersEntity.getCode())) {
                                    ToastUtil.initToast(getContext(), "分享文案已复制，去粘贴");

                                    YiJianTuiGuangDialog yiJianTuiGuangDialog = YiJianTuiGuangDialog.newInstance(house_materialEntity.getBody().get((Integer) view.getTag()).getHouse().getBrokerAge());
                                    yiJianTuiGuangDialog.show(getActivity().getFragmentManager());
                                    yiJianTuiGuangDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View v) {
                                            ClipboardManager mClipboardManager = mClipboardManager =
                                                    (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                                            ClipData mClipData;

                                            mClipData = ClipData.newPlainText("test", house_materialEntity.getBody().get((Integer) view.getTag()).getAdWord());
                                            mClipboardManager.setPrimaryClip(mClipData);
                                            switch (v.getId()) {
                                                case R.id.tv_wx: {
                                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                                    List<String> picList = new ArrayList<String>();
                                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }

                                                    /*if (house_materialEntity.getBody().get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {
                                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                                        } else {
                                                            picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPoster());

                                                        }

                                                    } else {

                                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {

                                                            *//*if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                                picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList()) ;
                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }else {

                                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                                    picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().get(j));
                                                                }



                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }*//*
                                                            for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                            }

                                                        } else {
                                                            picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());

                                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size() < 9) {
                                                                for (int j = 0; j < 9 - house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size(); j++) {
                                                                    //picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());
                                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                    }
                                                                }
                                                            }


                                                        }

                                                    }*/
                                                    ShareUtilse.shareImage(getContext(),0, picList,picList.get(picList.size()-1),"");

                                                }

                                                break;
                                                case R.id.tv_pyq: {
                                                    loadingDialog = LoadingDialog.newInstance("加载中");
                                                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                                                    List<String> picList = new ArrayList<String>();
                                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }

                                                   /* if (house_materialEntity.getBody().get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {
                                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                                        } else {
                                                            picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPoster());

                                                        }

                                                    } else {

                                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {

                                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                                picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList()) ;
                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }else {

                                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                                    picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().get(j));
                                                                }



                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }

                                                        } else {
                                                            picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());

                                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size() < 9) {
                                                                for (int j = 0; j < 9 - house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size(); j++) {
                                                                   // picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());
                                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                    }
                                                                }
                                                            }


                                                        }

                                                    }*/
                                                    ShareUtilse.shareImage(getContext(),1, picList,picList.get(picList.size()-1),"");

                                                }
                                                break;
                                                case R.id.tv_YJTG_save: {
                                                    List<String> picList = new ArrayList<>();
                                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }
                                                   /* if (house_materialEntity.getBody().get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {
                                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                                        } else {
                                                            picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPoster());

                                                        }

                                                    } else {

                                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {

                                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                                picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList()) ;
                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }else {

                                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                                    picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().get(j));
                                                                }



                                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                                }
                                                            }

                                                        } else {
                                                            picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());

                                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size() < 9) {
                                                                for (int j = 0; j < 9 - house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size(); j++) {
                                                                    //picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());
                                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                                    }
                                                                }
                                                            }


                                                        }

                                                    }*/
                                                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                                                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                                                    saveImageForRecursive(picList, picList.size(), loadingDialog);
                                                }
                                            }
                                        }
                                    });


                                } else {
                                    ToastUtil.initToast(getContext(), material_postersEntity.getMsg());
                                }
                            }

                        }

                        @Override
                        public void onFailure(String url, String error) {

                        }
                    });
                }


            }
            break;
            case R.id.tv_Save: {//保存

                ClipboardManager mClipboardManager = mClipboardManager =
                        (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);

                ClipData mClipData;

                mClipData = ClipData.newPlainText("test", house_materialEntity.getBody().get((Integer) view.getTag()).getAdWord());
                mClipboardManager.setPrimaryClip(mClipData);


                if (house_materialEntity.getBody().get((Integer) view.getTag()).getEnablePoster() == 0) {//enablePoster(1:可以生成 0:无法生成),

                    List<String> picList = new ArrayList<>();
                    picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());
                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                    saveImageForRecursive(picList, picList.size(), loadingDialog);


                } else {
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getActivity().getFragmentManager(), "loading");
                    String materialId = house_materialEntity.getBody().get((Integer) view.getTag()).getId();
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("modelType", house_materialEntity.getBody().get((Integer) view.getTag()).getModelType() + "");
                    OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.material_posters, materialId), hashMap, new OkHttpUtil.OnDataListener() {
                        @Override
                        public void onResponse(String url, String json) {
                            if (!TextUtils.isEmpty(json)) {
                                dismissLoading();
                                final Material_postersEntity202 material_postersEntity = gson.fromJson(json, Material_postersEntity202.class);
                                if ("200".equals(material_postersEntity.getCode())) {

                                    List<String> picList = new ArrayList<>();
                                    for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                    }
                                    /*if (house_materialEntity.getBody().get((Integer) view.getTag()).getMaterialType() == 1) {//为海报
                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {
                                            picList.add(material_postersEntity.getBody().getPosterList().get(0).getUrl());

                                        } else {
                                            picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPoster());

                                        }

                                    } else {

                                        if (house_materialEntity.getBody().get((Integer) view.getTag()).getReplacePic() == 1) {

                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size()+material_postersEntity.getBody().getPosterList().size()<=9){
                                                picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList()) ;
                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                }
                                            }else {

                                                for (int j = 0; j <9-material_postersEntity.getBody().getPosterList().size() ; j++) {
                                                    picList.add(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().get(j));
                                                }



                                                for (int j = 0; j < material_postersEntity.getBody().getPosterList().size(); j++) {
                                                    picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl()); ;
                                                }
                                            }

                                        } else {
                                            picList.addAll(house_materialEntity.getBody().get((Integer) view.getTag()).getPicList());

                                            if (house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size() < 9) {
                                                for (int j = 0; j < 9 - house_materialEntity.getBody().get((Integer) view.getTag()).getPicList().size(); j++) {
                                                    //picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());
                                                    if (j<material_postersEntity.getBody().getPosterList().size()){
                                                        picList.add(material_postersEntity.getBody().getPosterList().get(j).getUrl());

                                                    }
                                                }
                                            }


                                        }

                                    }*/
                                    LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                                    loadingDialog.show(getActivity().getFragmentManager(), "0");
                                    saveImageForRecursive(picList, picList.size(), loadingDialog);


                                } else {
                                    ToastUtil.initToast(getContext(), material_postersEntity.getMsg());
                                }
                            }

                        }

                        @Override
                        public void onFailure(String url, String error) {

                        }
                    });
                }


            }

        }

    }

    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {//递归保存
        if (loadingSaveDialog != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - img.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (img.size() != 0) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(getContext(), img.get(0), true);

                    img.remove(0);
                    saveImageForRecursive(img, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {
                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            ToastUtil.initToast(getContext(), "图文保存至" + fileName);

            ToastUtil.initToast(getContext(), "图文保存成功！快去发朋友圈推广吧~");
            Looper.loop();
        }

    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }
    }

    @Override
    public void onItemClick(View v, int position) {

    }

    @Override
    public void onCallback() {

    }





    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;

    //根据网络图片url路径保存到本地
    public final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri =context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (statusLayoutManager != null) {

                statusLayoutManager.showSuccessLayout();
            }
            if (String.format(Constant.URL.house_material, houseId).equals(url) || String.format(Constant.URL.presell_material, persellId).equals(url)) {
                LogeUtil.e("house_materialEntity", json);
                house_materialEntity = gson.fromJson(json, house_materialEntity.class);
                if ("200".equals(house_materialEntity.getCode())) {
                    dismissLoading();
                    fodderAdapter.setData(house_materialEntity.getBody());

                    boolean isTranslucentStatus = false;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                       /* Window window = getActivity().getWindow();
                        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                        window.setStatusBarColor(Color.TRANSPARENT);
                        window.setNavigationBarColor(Color.TRANSPARENT);
                        isTranslucentStatus = true;*/
                    }

                    vImageWatcher = ImageWatcher.Helper.with(getActivity()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                            .setTranslucentStatus(!isTranslucentStatus ? Utils.calcStatusBarHeight(getContext()) : 0) // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                            .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                            .setHintMode(ImageWatcher.POINT)//设置指示器（默认小白点）
                            .setHintColor(getResources().getColor(R.color.colorRed), getResources().getColor(R.color.colorWhite))//设置指示器颜色
                            .setOnPictureLongPressListener(this) // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
                            .setLoader(new ImageWatcher.Loader() {//调用show方法前，请先调用setLoader 给ImageWatcher提供加载图片的实现
                                @Override
                                public void load(Context context, String url, final ImageWatcher.LoadCallback lc) {
                                    Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                            lc.onResourceReady(resource);
                                        }

                                        @Override
                                        public void onLoadStarted(Drawable placeholder) {
                                            lc.onLoadStarted(placeholder);
                                        }

                                        @Override
                                        public void onLoadFailed(Drawable errorDrawable) {
                                            lc.onLoadFailed(errorDrawable);
                                        }
                                    });
                                }
                            })
                            .create();
                    Utils.fitsSystemWindows(isTranslucentStatus, v_fit);

                } else {
                    ToastUtil.initToast(getContext(), house_materialEntity.getMsg());
                }
            }
        }
    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
    }

    @Override
    public void onItemClick(final View v) {
        switch (v.getId()) {

            case R.id.tv_wx: {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(getContext(),0, images,images.get(images.size()-1),"");

            }
            break;
            case R.id.tv_pyq: {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(getContext(),1, images,images.get(images.size()-1),"");

            }
            break;
            case R.id.tv_save: {
                List<String> picList = new ArrayList<>();
                picList.add((String) v.getTag());
                LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picList.size() + "张");
                loadingDialog.show(getActivity().getFragmentManager(), "0");
                saveImageForRecursive(picList, picList.size(), loadingDialog);

            }
            break;
        }
    }


    @Override
    public void onThumbPictureClick(ImageView i, List<ImageView> imageGroupList, List<String> urlList) {

        vImageWatcher.show(i, imageGroupList, urlList);

    }


    @Override
    public boolean onBackPressed() {
        if (vImageWatcher == null) {
            return false;
        } else {
            // 当确认没有子Fragmnt时可以直接return false
            if (!vImageWatcher.handleBackPressed()) {
                return BackHandlerHelper.handleBackPress(this);
            } else {
                return !BackHandlerHelper.handleBackPress(this);
            }
        }


    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }

    @Override
    public void onResume() {
        super.onResume();
        dismissLoading();
    }

    @Override
    public void onRefresh() {
        loadData();
    }


}
